package com.libre.security;

import com.libre.auth.entity.Role;
import com.libre.auth.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义User类实现UserDetails
 */
public class SecurityUser extends User implements UserDetails {


//    List<Role> roles;

    //构造方法
    public SecurityUser(User user) {
        if (user != null) {
            // 把当前登录用户的信息，交给 SecurityUser
            BeanUtils.copyProperties(user, this);
            System.out.println("user=========="+user);
//            roles = user.getRoles();
        }
    }

    // 获取用户的权限集合：getAuthorities()获取当前用户所具有的角色
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        List<Role> roles = super.getRoles();
        System.out.println("roles-----"+roles);
        if (roles != null) {
            for (Role role : roles) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getCode());
                authorities.add(authority);
            }
        }
        return authorities;
    }

    //账号是否没过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //账号是否没被锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //密码是否没过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //账户是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
